<?php
/**
 * @return
 * @author 朱乐斌
 * @date
 */

namespace app\api\controller;

use app\api\model\AdminModel;
use app\api\model\CodeModel;
use app\api\validate\loginValidate;
use app\api\validate\registerCode;
use app\api\validate\registerCodeValidate;
use app\BaseController;
use Firebase\JWT\JWT;
use think\Exception;

class Login extends BaseController
{
    protected $key = 'qt';

    /**
     *  用户登录
     */
    public function login()
    {
        try {
            // 接收用户传输的数据
            $data = $this->request->post();
            if ($data['mobile'] == '') {
                return json(['msg' => '手机号不能为空']);
            }
            if ($data['password'] == '') {
                return json(['msg' => '密码不能为空']);
            }
            // 验证数据
//            validate(loginValidate::class)->scene('login')->check($data);
            // 实例化模型
            $model = new \app\api\model\AdminModel();
            // 查询用户是否存在
            $mobile = $model->where('mobile', '=', $data['mobile'])->find();
            if (empty($mobile)) return json(['msg' => '用户不存在']);
            // 判断用户密码是否正确
            if (md5($data['password']) != $mobile['password']) return json(['msg' => '密码错误']);
            // 登录成功生成JWT
            $payload = [
                // 签发人
                'iss' => "zlb",
                // 签发时间
                'iat' => time(),
                // 过期时间
                'exp' => time() + 43200,
                // 自定义数据
                'data' => [
                    'mobile' => $mobile,
                ]
            ];
            $jwt = JWT::encode($payload, $this->key, 'HS256');
            return json(['code' => 1, 'msg' => '登录成功', 'token' => $jwt]);
        } catch (Exception $e) {
            return json($e->getMessage());
        }
    }


    /**
     *  获取验证码
     */
    public function registerCode()
    {
        try {
            // 接收手机号
            $data = $this->request->post();
            // 验证数据
            validate(registerCodeValidate::class)->check($data);
            // 生成验证码
            $code = rand(100000, 999999);
            $codeModel = new CodeModel();
            $codeData = [
                'mobile' => $data['mobile'],
                'code' => $code,
            ];
            $codeModel = $codeModel->save($codeData);
            // 发送验证码
            if ($codeModel) return json(['msg' => '验证码发送成功', 'code' => $code]);
            return json(['msg' => '验证码发送失败']);
        } catch (Exception $e) {
            return errMsg($e->getMessage());
        }

    }

    /**
     * 用户注册
     */
    public function register()
    {
        try {
            // 接收数据
            $data = $this->request->post();
            // 验证数据
//            $validator = validate(loginValidate::class)->scene('register');
//            if (!$validator->check($data)) {
//                return json(['msg' => $validator->getError()]);
//            }

            // 查询是否已注册
            $adminModel = new \app\api\model\AdminModel;
            $userExists = $adminModel->where('mobile', $data['mobile'])->find();
            if (!empty($userExists)) {
                return json(['msg' => '用户已存在']);
            }

            // 查询验证码
            $codeModel = new \app\api\model\CodeModel;
            $codeData = $codeModel->where('mobile', $data['mobile'])->find();
            if (empty($codeData)) {
                return json(['msg' => '您没有发送验证码']);
            }

            // 验证验证码
            if ($codeData['code'] != $data['code']) {
                return json(['msg' => '验证码错误']);
            }

            // 判断两次密码是否相同
            if ($data['password'] != $data['password2']) {
                return json(['msg' => '两次密码不一致']);
            }

            $mobile = substr($data['mobile'], -4);
            $user = "取图用户_";
            // 保存用户信息
            $userData = [
                'mobile' => $data['mobile'],
                'nickname' => $user . $mobile,
                'password' => md5($data['password']),
            ];
            $result = $adminModel->save($userData);

            if ($result) {
                // 删除验证码
                $codeData->delete();
                return json(['msg' => '注册成功']);
            } else {
                return json(['msg' => '注册失败']);
            }
        } catch (\Exception $e) {
            return errMsg($e->getMessage());
        }
    }


}